package main.java.com.yanglq.expresssearch.action;

import main.java.com.yanglq.expresssearch.model.DatasVo;
import main.java.com.yanglq.expresssearch.model.ResultsVo;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Objects;
import java.util.Scanner;

/**
 * Created by yanglq on 2017/1/20.
 */
public class ExpresssQuery {
    static String[] Propertys = {"顺丰", "圆通", "申通", "中通", "百世",
            "天天", "韵达", "EMS", "邮政", "全峰", "京东", "宅急送", "德邦", "优速", "快捷", "国通"};

    public static void main(String[] args) throws Exception {

        String postid = "";
        for (int i = 0; i < Propertys.length; i++) {
            postid += Propertys[i] + ", ";
        }
        System.out.println("支持的快递公司如下:");
        System.out.print(postid);
        postid = null;
        System.out.println("\n");
        while (true) {
            System.out.println("请输入快递公司名称（例：顺丰，天天），完成后按回车键。如要退出请按“q");
            Scanner sc = new Scanner(System.in);
            String str1 = sc.nextLine().trim();
            if (str1.equals("q") || str1.equals("Q")) {
                return;
            }
            boolean isTrue = false;
            for (String name : Propertys
                    ) {
                if (name.equals(str1)) {
                    isTrue = true;
                    break;
                }
            }
            String type;
            if (!isTrue) {
                System.out.println("别闹，请输入正确的快递公司名称OK？" + "\n");
                continue;
            } else {
                type = getExpressCompany(str1);
            }
            System.out.println("请输入快递单号，完成后按回车键");
            String str2 = sc.nextLine().trim();
            if (checkNumber(str2)) {
                postid = str2;
                captureJavascript(str1, type, postid);
            } else {
                System.out.println("请输入正确的快递单号OK ?");
            }
        }
    }

    private static boolean checkNumber(String value) {
        String regex = "^(-?[1-9]\\d*\\.?\\d*)|(-?0\\.\\d*[1-9])|(-?[0])|(-?[0]\\.\\d*)$";
        return value.matches(regex);
    }

    private static String getExpressCompany(String str1) {
        String name = null;
        switch (str1) {
            case "顺丰":
                name = "shunfeng";
                break;
            case "圆通":
                name = "yuantong";
                break;
            case "申通":
                name = "shentong";
                break;
            case "百世":
                name = "huitongkuaidi";
                break;
            case "中通":
                name = "zhongtong";
                break;
            case "天天":
                name = "tiantian";
                break;
            case "韵达":
                name = "yunda";
                break;
            case "EMS":
                name = "ems";
                break;
            case "邮政":
                name = "youzhengguonei";
                break;
            case "全峰":
                name = "quanfengkuaidi";
                break;
            case "京东":
                name = "jd";
                break;
            case "宅急送":
                name = "zhaijisong";
                break;
            case "德邦":
                name = "debangwuliu";
                break;
            case "优速":
                name = "youshuwuliu";
                break;
            case "快捷":
                name = "kuaijiesudi";
                break;
            case "国通":
                name = "guotongkuaidi";
                break;
            default:
                break;
        }
        return name;
    }


    public static void captureJavascript(String company, String type, String postid) throws Exception {
        String strURL = "http://www.kuaidi100.com/query?type=" + type + "&postid=" + postid + "&id=1&valicode=&temp=0";
        URL url = new URL(strURL);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        InputStreamReader input = new InputStreamReader(httpConn
                .getInputStream(), "utf-8");
        BufferedReader bufReader = new BufferedReader(input);
        String line = "";
        StringBuilder contentBuf = new StringBuilder();
        while ((line = bufReader.readLine()) != null) {
            contentBuf.append(line);
        }
        //转换成json数据处理
        ResultsVo vo = null;
        vo = toJSON(contentBuf);
//        //结果展示
        showResult(vo, company);
    }

    private static void showResult(ResultsVo vo, String company) {
        System.out.println("-------------------您查询的快递结果如下---------------------------");
        System.out.println("快递公司： " + company + "快递");
        System.out.println("快递单号： " + vo.getNu());
        final String s = Objects.equals(vo.getStatus(), "200") ? "查询成功" : "查询失败，请重试！";
        System.out.println("查询状态： " + s);
        if (!Objects.equals(vo.getMessage(), "ok")) {
            System.out.println("错误原因： " + vo.getMessage());
        }
        DatasVo[] dvs = vo.getData();

        for (DatasVo dv : dvs) {
//            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            System.out.println("时间： " + dv.getTime());
            System.out.println("快递信息： " + dv.getContext());
            System.out.println("快递位置： " + dv.getLocation());
            System.out.println("------------------------------------------------------");
        }
    }

    private static ResultsVo toJSON(StringBuilder contentBuf) {
        String jsonString = contentBuf.toString();
        JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON(jsonString);
        return (ResultsVo) JSONObject.toBean(jsonObject, ResultsVo.class);
    }
}
